import VueRouter from "vue-router";
import Vue from "vue";
import store from "@/store";
import { Message } from 'element-ui'
Vue.use(VueRouter);

import routes from "./routes"
// 重写push和replace方法
const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

// 自定义其回调函数(重写的目的是当程序出现错误的时候不会中断并且可以做相应的处理)
VueRouter.prototype.push = function (location, resolve, reject) {
    resolve = resolve || function () { };
    // 这样重写是为了解决路由冗余的问题
    reject = reject || function () {};

    originPush.call(this,location, resolve, reject)

    // 不能这么写，因为修改函数名的数据不能修改arguments
    // originPush.call(this,...arguments)
}

VueRouter.prototype.replace = function (location, resolve, reject) {
    resolve = resolve || function () { };
    reject = reject || function () {};


    originReplace.call(this,location, resolve, reject)

    // originReplace.call(this, ...arguments)
}

const router = new VueRouter({
    // 配置路由
    routes,
    scrollBehavior() {
        return { y: 0 }
    },
})

// 需要登录才能进入的网页
let needTokenPath = ['/shopcart', '/pay', '/paysuccess', '/trade', '/userspace']
// 定义全局路由守卫
router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;
    let userName = store.state.user.userInfo.userName;
    if (token) {
        // 如果用户登录了，不能去往的页面
        if (to.path.indexOf('/login') != -1 || to.path.indexOf('/register') != -1) {
            next('/home');
        } else {
            // 用户登录了可以去往的页面
            if (userName) {
                next();
            } else {
                // 若是没有用户名，则要获取用户信息
                try {
                    await store.dispatch("user/getUserInfo");
                    next();
                } catch (error) {
                    Message({
                        message: error,
                        type: "error"
                    })
                    // 如果有问题直接清空用户信息，不然会一直重复发送请求直到成功为止
                    store.dispatch("user/userLogout");
                    next("/login");
                }
            }
        }
    } else {
        // 如果没有token
        if (needTokenPath.some(item => to.path.indexOf(item) != -1)) {
            Message({
                message: "请先登录",
                type: "info"
            })
            next("login?redirect=" + to.path);
        } else {
            next();
        }
    }
})

export default router;
